'use strict';

const { Service } = require('egg');
const ModelName = 'DeviceInfo'
class RouterService extends Service {
    // 所有列表
    async allList(where) {
        return this.ctx.model[ModelName].findAll({
            where,
            order:[
                // id 降序
            ],
        });
    }
    async refresh() {
        const dailySummaryList = await this.ctx.model.DailySummary.findAll({
            raw: true
        });
        // 汇总统计将不同farm_id的device_id的数据进行汇总
        const summary = dailySummaryList.reduce((acc, cur) => {
            if (!acc[cur.device_id]) {
                acc[cur.device_id] = {
                    device_id: cur.device_id,
                    device_name: cur.device_id,
                    farm_id: cur.farm_id,
                }
            }
            return acc;
        }, {});
        let deviceList = Object.values(summary)
        // 删除所有设备
        await this.ctx.model.DeviceInfo.destroy({
            where: {},
            truncate: true
        });
        // 插入设备表
        // 如果farm_id和device_id都相同则不插入
        for (let i = 0; i < deviceList.length; i++) {
            await this.ctx.model.DeviceInfo.create(deviceList[i]);
        }
        return deviceList;
    }
}

module.exports = RouterService;
